package com.winhxd.b2c.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.domain.PagedList;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.CustomerInfoCondition;
import com.winhxd.b2c.common.domain.customer.condition.CustomerMyRevenueCondition;
import com.winhxd.b2c.common.domain.customer.condition.CustomerTotalCondition;
import com.winhxd.b2c.common.domain.customer.enums.CustomerUserLevelEnum;
import com.winhxd.b2c.common.domain.customer.vo.CustomerRevenueVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerTotalVO;
import com.winhxd.b2c.common.domain.customer.vo.CustomerUserInfoVO;
import com.winhxd.b2c.common.domain.order.condition.OrderProfitSummaryCondition;
import com.winhxd.b2c.common.domain.order.condition.OrderSalesSummaryCondition;
import com.winhxd.b2c.common.domain.order.condition.OrderSummaryCondition;
import com.winhxd.b2c.common.domain.order.condition.OrderUsersCondition;
import com.winhxd.b2c.common.domain.order.vo.*;
import com.winhxd.b2c.common.exception.BusinessException;
import com.winhxd.b2c.common.feign.customer.CustomerServiceClient;
import com.winhxd.b2c.common.util.DateUtil;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.order.dao.OrderInfoMapper;
import com.winhxd.b2c.order.dao.OrderRebateRecordMapper;
import com.winhxd.b2c.order.service.OrderDataStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Author lijianhua
 * @Description //订单数据
 * @Date 13:56 2019/1/8
 **/
@Service
public class OrderDataStatisticsServiceImpl implements OrderDataStatisticsService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderRebateRecordMapper orderRebateRecordMapper;
    @Autowired
    private CustomerServiceClient customerServiceClient;
    @Autowired
    private Cache cache;
    public final int LEVEL_0 = 0;
    public final int LEVEL_1 = 1;
    public final int LEVEL_2 = 2;
    private final int EXPIRE_PLAT=10*60;
    @Override
    public OrderBusinessSummaryVO getBusinessSummarySummary(OrderSalesSummaryCondition condition) {
        String key= CacheName.CACHE_KEY_PLAT_FORM;
        OrderBusinessSummaryVO vo = new OrderBusinessSummaryVO();
        if(false){
            vo=JsonUtil.parseJSONObject(cache.get(key),OrderBusinessSummaryVO.class);
        }else {
            //今日销售额:本日截止当前时刻已支付且未确认退款的销售额
            BigDecimal salesToday = orderInfoMapper.selectSalesToday(condition);
            //今日新增订单:本日截止当前时刻已支付且未确认退款的销售额
            Integer orderNumsToday = orderInfoMapper.selectOrderNumsToday(condition);
            //待发货:显示当前订单状态处于“待发货”的订单数
            Integer orderSendOutNum = orderInfoMapper.selectOrderSendOutNum(condition);
            //售后中:显示当前进行中的售后单数量
            Integer orderServiceNum = orderInfoMapper.selectOrderServiceNum(condition);

            vo.setSalesToday(salesToday);
            vo.setOrderNumsToday(orderNumsToday);
            vo.setOrderSendOutNum(orderSendOutNum);
            vo.setOrderServiceNum(orderServiceNum);
            vo.setData(DateUtil.format(new Date(), "yyyy-MM-dd hh:mm:ss"));

            cache.set(key, JsonUtil.toJSONString(vo));
            cache.expire(key, EXPIRE_PLAT);
        }
        return vo;
    }

    @Override
    public Order4meSummaryVO get4meSummarySummary(OrderSalesSummaryCondition condition) {
        Order4meSummaryVO vo = new Order4meSummaryVO();
        //用户待付款订单量
        Integer unPayedNum = orderInfoMapper.selectUnPayedNum(condition);
        //用户待发货订单量
        Integer unSendedNum = orderInfoMapper.selectUnSendedNum(condition);
        //用户待收货订单量"
        Integer unReceiveNum = orderInfoMapper.selectUnReceiveNum(condition);
        //用户已收货订单量"
        Integer receivedNum = orderInfoMapper.selectReceivedNum(condition);
        //用户待售后订单量
        Integer unServicedNum = orderInfoMapper.selectUnServicedNum(condition);

        vo.setUnPayedNum(unPayedNum);
        vo.setUnReceiveNum(unReceiveNum);
        vo.setUnSendedNum(unSendedNum);
        vo.setUnServicedNum(unServicedNum);
        vo.setReceivedNum(receivedNum);
        return vo;
    }

    @Override
    public Order4meSummaryVO get4OneSummarySummary(OrderSalesSummaryCondition condition) {
        Order4meSummaryVO vo = new Order4meSummaryVO();
        Map<String,Object> params = new HashMap<String,Object> ();
        params.put("customerId", condition.getCustomerId());
        //用户待付款订单量
        params.put("status", "1");
        Integer unPayedNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户待发货订单量
        params.put("status", "3");
        Integer unSendedNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户待收货订单量"
        params.put("status", "4");
        Integer unReceiveNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户已收货订单量"
        params.put("status", "5");
        Integer receivedNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户待售后订单量
        Integer unServicedNum = orderInfoMapper.selectUnServicedNumByCustomerId(condition);
        vo.setUnPayedNum(unPayedNum);
        vo.setUnReceiveNum(unReceiveNum);
        vo.setUnSendedNum(unSendedNum);
        vo.setUnServicedNum(unServicedNum);
        vo.setReceivedNum(receivedNum);
        return vo;
    }

    @Override
    public Order4meSummaryVO get4TwoSummarySummary(OrderSalesSummaryCondition condition) {
        Order4meSummaryVO vo = new Order4meSummaryVO();
        Map<String,Object> params = new HashMap<String,Object> ();
        params.put("customerId", condition.getCustomerId());
        //用户待付款订单量
        params.put("status", "1");
        Integer unPayedNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户待发货订单量
        params.put("status", "3");
        Integer unSendedNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户待收货订单量"
        params.put("status", "4");
        Integer unReceiveNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户已收货订单量"
        params.put("status", "5");
        Integer receivedNum = orderInfoMapper.selectCountNumByCustomerIdAndStatus(params);
        //用户待售后订单量
        Integer unServicedNum = orderInfoMapper.selectUnServicedNumByCustomerId(condition);
        vo.setUnPayedNum(unPayedNum);
        vo.setUnReceiveNum(unReceiveNum);
        vo.setUnSendedNum(unSendedNum);
        vo.setUnServicedNum(unServicedNum);
        vo.setReceivedNum(receivedNum);
        return vo;
    }

    @Override
    public OrderDistributionOneSummaryVO getOrderDistributionOneSummary(OrderSalesSummaryCondition condition) {
        OrderDistributionOneSummaryVO vo = new OrderDistributionOneSummaryVO();

        CustomerMyRevenueCondition myRevenueCondition = new CustomerMyRevenueCondition();
        myRevenueCondition.setCustomerId(condition.getCustomerId());
        myRevenueCondition.setLevel(condition.getLevel());
        //获取实际收益 积分 可提现金额
        CustomerRevenueVO customerRevenuere = customerServiceClient.getCustomerRevenue(myRevenueCondition).getDataWithException();

        CustomerTotalCondition customerTotalCondition = new CustomerTotalCondition();
        customerTotalCondition.setCustomerId(condition.getCustomerId());
        customerTotalCondition.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
        ResponseResult<CustomerTotalVO> result = customerServiceClient.getCustomerTotalById(customerTotalCondition);

        //访客跟踪
        vo.setCustomerTotal(result.getDataWithException());
        //订单
        vo.setOrder(getOrder(condition));
        //总收益
        vo.setTotal(getTotal(condition, customerRevenuere));
        //线下收益
        vo.setReferrals(getReferrals(condition, customerRevenuere));
        //设置积分
        if (customerRevenuere.getRemainIntegral() != null) {
            vo.setActualIntegral(customerRevenuere.getRemainIntegral());
        }
        //已提现金额
        vo.setWithdraw(customerRevenuere.getWithdraw());
        vo.setBalance(customerRevenuere.getBalance());

        return vo;
    }

    /**
     * @return com.winhxd.b2c.common.domain.order.vo.OrderDistributionOrderSummaryVO
     * @Author lijianhua
     * @Description //订单跟踪
     * @Date 14:41 2019/1/9
     * @Param [condition]
     **/
    private OrderDistributionOrderSummaryVO getOrder(OrderSalesSummaryCondition condition) {
        OrderDistributionOrderSummaryVO vo = new OrderDistributionOrderSummaryVO();
        //今日新增订单
        Integer orderNumsToday = orderInfoMapper.selectOrderNumsTodayAgentOne(condition);
        //我的今日新增订单
        Integer orderNumsTodayForMe = orderInfoMapper.selectOrderNumsTodayForMeAgentOne(condition);
        //线下今日新增订单
        //Integer orderNumsTodayForReferrals = orderInfoMapper.selectOrderNumsTodayForReferralsAgentOne(condition);
        Integer orderNumsTodayForReferrals = orderNumsToday - orderNumsTodayForMe;

        vo.setOrderNumsToday(orderNumsToday);
        vo.setOrderNumsTodayForReferrals(orderNumsTodayForReferrals);
        vo.setOrderNumsTodayForMe(orderNumsTodayForMe);
        return vo;
    }


    @Override
    public PagedList<OrderProfitVO> findDistOneOrderProfitSummary(OrderProfitSummaryCondition condition) {
        PagedList<OrderProfitVO> pagedList = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<OrderProfitVO> list = orderRebateRecordMapper.selectDistOneOrderProfitSummary(condition);
        PageInfo<OrderProfitVO> pageInfo = new PageInfo<>(list);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(pageInfo.getPageNum());
        pagedList.setPageSize(pageInfo.getPageSize());
        pagedList.setTotalRows(pageInfo.getTotal());
        setUserInfo(pagedList);
        setProfit(pagedList, CustomerUserLevelEnum.CUSTOMER_LEVEL_1.getCode());
        return pagedList;
    }


    @Override
    public PagedList<OrderProfitVO> findDistOneOrderReferralsProfitSummary(OrderProfitSummaryCondition condition) {
        PagedList<OrderProfitVO> pagedList = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<OrderProfitVO> list = orderRebateRecordMapper.selectDistOneOrderReferralsProfitSummary(condition);
        PageInfo<OrderProfitVO> pageInfo = new PageInfo<>(list);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(pageInfo.getPageNum());
        pagedList.setPageSize(pageInfo.getPageSize());
        pagedList.setTotalRows(pageInfo.getTotal());
        setUserInfo(pagedList);
        return pagedList;
    }

    @Override
    public OrderDistributionTwoSummaryVO getOrderDistributionTwoSummary(OrderSalesSummaryCondition condition) {

        CustomerMyRevenueCondition myRevenueCondition = new CustomerMyRevenueCondition();
        myRevenueCondition.setCustomerId(condition.getCustomerId());
        myRevenueCondition.setLevel(condition.getLevel());
        //获取实际收益 积分 可提现金额
        CustomerRevenueVO customerRevenuere = customerServiceClient.getCustomerRevenue(myRevenueCondition).getDataWithException();

        OrderDistributionTwoSummaryVO vo = new OrderDistributionTwoSummaryVO();
        //订单
        vo.setOrder(getOrderTwo(condition));
        //收益
        vo.setTotal(getTotalTwo(condition, customerRevenuere));
        //我的积分
        //设置积分
        if (customerRevenuere.getRemainIntegral() != null) {
            vo.setActualIntegral(customerRevenuere.getRemainIntegral());
        }
        //可提现金额
        vo.setWithdraw(customerRevenuere.getWithdraw());
        CustomerTotalCondition customerTotalCondition = new CustomerTotalCondition();
        customerTotalCondition.setCustomerId(condition.getCustomerId());
        customerTotalCondition.setLevel(CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode());
        ResponseResult<CustomerTotalVO> result = customerServiceClient.getCustomerTotalById(customerTotalCondition);

        //订单跟踪
        vo.setCustomerTotal(result.getDataWithException());
        return vo;
    }

    /**
     * @return com.winhxd.b2c.common.domain.order.vo.OrderDistributionOrderSummaryVO
     * @Author lijianhua
     * @Description //订单跟踪
     * @Date 14:41 2019/1/9
     * @Param [condition]
     **/
    private OrderDistributionOrderSummaryVO getOrderTwo(OrderSalesSummaryCondition condition) {
        OrderDistributionOrderSummaryVO vo = new OrderDistributionOrderSummaryVO();
        //今日新增订单
        Integer orderNumsToday = orderInfoMapper.selectOrderNumsTodayAgentTwo(condition);
        vo.setOrderNumsToday(orderNumsToday);
        return vo;
    }


    @Override
    public PagedList<OrderProfitVO> findDistTwoOrderProfitSummary(OrderProfitSummaryCondition condition) {
        PagedList<OrderProfitVO> pagedList = new PagedList<>();
        PageHelper.startPage(condition.getPageNo(), condition.getPageSize());
        List<OrderProfitVO> list = orderRebateRecordMapper.selectDistTwoOrderProfitSummary(condition);
        PageInfo<OrderProfitVO> pageInfo = new PageInfo<>(list);
        pagedList.setData(pageInfo.getList());
        pagedList.setPageNo(pageInfo.getPageNum());
        pagedList.setPageSize(pageInfo.getPageSize());
        pagedList.setTotalRows(pageInfo.getTotal());
        setUserInfo(pagedList);
        setProfit(pagedList, CustomerUserLevelEnum.CUSTOMER_LEVEL_2.getCode());
        return pagedList;
    }


    @Override
    public List<OrderUsersProfitListVO> findOrderUsersProfitList(OrderUsersCondition condition) {
        List<OrderUsersProfitListVO> list = orderRebateRecordMapper.selectOrderUsersProfitList(condition);
        return list;
    }

    @Override
    public OrderUserBaseSummaryVO getUserBaseSummarySummary(OrderSummaryCondition condition) {
        OrderUserBaseSummaryVO vo = new OrderUserBaseSummaryVO();

        //待转正金额
        BigDecimal total = BigDecimal.ZERO;
        //订单数
        Integer orderNum = 0;
        switch (condition.getUserLevel()) {
            case LEVEL_0:
                total = orderRebateRecordMapper.selectWaitingTotal(condition);
                break;
            case LEVEL_1:
                total = orderRebateRecordMapper.selectWaitingTotalAgentOne(condition);
                break;
            case LEVEL_2:
                total = orderRebateRecordMapper.selectWaitingTotalAgentTwo(condition);
                break;
            default:
                BusinessException e = new BusinessException();
                e.setErrorCode(BusinessCode.CODE_1001);
                throw e;
        }

        orderNum = orderInfoMapper.selectOrderNum(condition);
        vo.setOrderNum(orderNum);
        vo.setTotal(total);
        return vo;
    }

    /**
     * @return void
     * @Author lijianhua
     * @Description //设置实际收益
     * @Date 9:13 2019/1/12
     * @Param [pagedList]
     **/
    private void setProfit(PagedList<OrderProfitVO> pagedList, int level) {
        CustomerInfoCondition condition = new CustomerInfoCondition();
        List<String> orderList = new ArrayList<>();
        if (pagedList.getData() == null || pagedList.getData().isEmpty()) {
            return;
        }
        pagedList.getData().forEach((vo) -> orderList.add(vo.getOrderNo()));
        //TODO 订单收益
    }

    /**
     * @return void
     * @Author lijianhua
     * @Description //设置用户信息
     * @Date 9:46 2019/1/10
     * @Param []
     **/
    private void setUserInfo(PagedList<OrderProfitVO> pagedList) {
        CustomerInfoCondition condition = new CustomerInfoCondition();
        List<Long> userList = new ArrayList<>();
        if (pagedList.getData() == null || pagedList.getData().isEmpty()) {
            return;
        }
        pagedList.getData().forEach((vo) -> userList.add(vo.getCustomerId()));
        condition.setCustomerIds(userList);
        ResponseResult<List<CustomerUserInfoVO>> result = customerServiceClient.getCustomerUserInfoByIds(condition);

        List<CustomerUserInfoVO> list = result.getDataWithException();
        if (list != null) {
            for (OrderProfitVO vo : pagedList.getData()) {
                for (CustomerUserInfoVO user : list) {
                    if (user.getId().longValue() == vo.getCustomerId().longValue()) {
                        vo.setHeadImg(user.getHeadImg());
                        vo.setNickName(user.getNickName());
                        vo.setWechatName(user.getWechatName());
                        if(vo.getStoreName()==null) {
                            vo.setStoreName(user.getStoreName());
                        }
                        break;
                    }
                }
            }
        }
    }

    /**
     * @return com.winhxd.b2c.common.domain.order.vo.OrderDistributionTotalSummaryVO
     * @Author lijianhua
     * @Description //的总收益
     * @Date 14:41 2019/1/9
     * @Param [condition]
     **/
    private OrderDistributionTotalSummaryVO getTotalTwo(OrderSalesSummaryCondition condition, CustomerRevenueVO customerRevenuere) {

        OrderDistributionTotalSummaryVO vo = new OrderDistributionTotalSummaryVO();
        //我的总收益
        BigDecimal total = customerRevenuere.getTotalRevenue();
        if (total == null) {
            total = BigDecimal.ZERO;
        }
        //今日预估
        BigDecimal totalToday = orderRebateRecordMapper.selectTotalTodayAgentTwo(condition);
        //本周预估
        BigDecimal totalWeek = orderRebateRecordMapper.selectTotalWeekAgentTwo(condition);
        //本月预估
        BigDecimal totalMonth = orderRebateRecordMapper.selectTotalMonthAgentTwo(condition);
        vo.setTotal(total);
        vo.setTotalToday(totalToday);
        vo.setTotalMonth(totalMonth);
        vo.setTotalWeek(totalWeek);
        //可提现
        vo.setWithdraw(customerRevenuere.getWithdraw());
        vo.setBalance(customerRevenuere.getBalance());
        return vo;
    }

    /**
     * @return com.winhxd.b2c.common.domain.order.vo.OrderDistributionTotalSummaryVO
     * @Author lijianhua
     * @Description //的总收益
     * @Date 14:41 2019/1/9
     * @Param [condition]
     **/
    private OrderDistributionTotalSummaryVO getTotal(OrderSalesSummaryCondition condition, CustomerRevenueVO customerRevenuere) {
        //我的总收益
        OrderDistributionTotalSummaryVO vo = new OrderDistributionTotalSummaryVO();
        //我的总收益
        BigDecimal total = customerRevenuere.getTotalRevenue();
        if (total == null) {
            total = BigDecimal.ZERO;
        }
        //今日预估
        BigDecimal totalToday = orderRebateRecordMapper.selectTotalTodayAgentOne(condition);
        //本周预估
        BigDecimal totalWeek = orderRebateRecordMapper.selectTotalWeekAgentOne(condition);
        //本月预估
        BigDecimal totalMonth = orderRebateRecordMapper.selectTotalMonthAgentOne(condition);
        vo.setTotal(total);
        vo.setTotalToday(totalToday);
        vo.setTotalMonth(totalMonth);
        vo.setTotalWeek(totalWeek);
        //可提现金额
        vo.setWithdraw(customerRevenuere.getWithdraw());
        vo.setBalance(customerRevenuere.getBalance());
        return vo;
    }

    /**
     * @return com.winhxd.b2c.common.domain.order.vo.OrderDistributionReferralsSummaryVO
     * @Author lijianhua
     * @Description //我的线下收益
     * @Date 14:50 2019/1/9
     * @Param [condition]
     **/
    private OrderDistributionReferralsSummaryVO getReferrals(OrderSalesSummaryCondition condition, CustomerRevenueVO customerRevenuere) {
        OrderDistributionReferralsSummaryVO vo = new OrderDistributionReferralsSummaryVO();
        //我的线下收益
        BigDecimal total = customerRevenuere.getLowerRevenue();
        if (total == null) {
            total = BigDecimal.ZERO;
        }
        //今日预估
        BigDecimal totalToday = orderRebateRecordMapper.selectReferralsTotalToday(condition);
        //本周预估
        BigDecimal totalWeek = orderRebateRecordMapper.selectReferralsTotalWeek(condition);
        //本月预估
        BigDecimal totalMonth = orderRebateRecordMapper.selectReferralsTotalMonth(condition);
        vo.setTotal(total);
        vo.setTotalToday(totalToday);
        vo.setTotalMonth(totalMonth);
        vo.setTotalWeek(totalWeek);
        return vo;
    }
}
